package cn.cdzdjd.controller;

import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import cn.cdzdjd.constant.LocationRedirect;
import cn.cdzdjd.util.UrlUtil;
import cn.hutool.core.lang.UUID;
import lombok.extern.slf4j.Slf4j;

@RestController
@RequestMapping("/api")
@Slf4j
public class VideoDownlaodController {

	@Resource
	private RestTemplate restTemplate;

	@GetMapping("/download/video")
	public ResponseEntity<?> downlaodVideo(@RequestParam String url, HttpServletResponse response)
			throws UnsupportedEncodingException {
		String urlDecode = UrlUtil.decodeURL(url);
		String locationUrl = LocationRedirect.getLocationMobile(urlDecode);
		URLConnection urlConnection = null;
		try {
			URL address = new URL(locationUrl);
			urlConnection = address.openConnection();
			urlConnection.setRequestProperty("Referer", locationUrl); // 设置协议
			urlConnection.setRequestProperty("Sec-Fetch-Mode", "no-cors");
			urlConnection.setRequestProperty("User-Agent",
					"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36");
			urlConnection.setConnectTimeout(10 * 1000);
			HttpHeaders headers = new HttpHeaders();
			// 通知浏览器以下载方式(attachment)打开文件
			headers.setContentDispositionFormData("attachment", UUID.randomUUID().toString() + ".mp4");
			// 定义以二进制流数据(最常见的文件下载)的形式下载返回文件数据
			headers.setContentType(new MediaType("video", "mp4"));
			// 使用spring mvc框架的ResponseEntity对象封装返回下载数据
			byte[] bytes = IOUtils.toByteArray(urlConnection);
			log.info("服务器下载结束,下载内容大小为：" + bytes.length);
			return new ResponseEntity<byte[]>(bytes, headers, HttpStatus.OK);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

}
